package com.demo.service;

import com.demo.dao.DepartmentDao;
import com.demo.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    DepartmentDao departmentDao;

    @Override
    public int save(Department department) {
        return departmentDao.save(department);
    }

    @Override
    public int delete(int id) {
        return departmentDao.delete(id);
    }

    @Override
    public int deleteAll() {
        return departmentDao.deleteAll();
    }

    @Override
    public Department getOne(int id) {
        Department department = departmentDao.getOne(id);
        if (department.getSuper_id()!=0){
            department.setDepartment(departmentDao.getOne(department.getSuper_id()));
        }
        department.setTreeList(departmentDao.getListBySuperId(id));
        return department;
    }

    @Override
    public List<Department> getAll() {
        return departmentDao.getAll();
    }

    @Override
    public int modify(Department department) {
        return departmentDao.modify(department);
    }

    @Override
    public int findTotals() {
        return departmentDao.findTotals();
    }

    @Override
    public List<Department> findByPage(Integer pageNow, Integer pageSize) {
        int start = (pageNow - 1) * pageSize;
        return departmentDao.findByPage(start, pageSize);
    }

    @Override
    public List<Department> treeList() {
        List<Department> data = departmentDao.getAll();
        List<Department> departmentList = new ArrayList<>();
        for(Department department : data){
            if(department.getSuper_id() == 0){
                departmentList.add(department);
            }
        }
        for(Department department : departmentList){
            department.setTreeList(getChilde(department.getId(), data));
        }
        return departmentList;
    }

    @Override
    public List<Department> getChilde(int id, List<Department> rootList) {
        //子菜单
        List<Department> childList = new ArrayList<>();
        for(Department department : rootList){
            if(department.getSuper_id()==id){
                childList.add(department);
            }
        }
        for(Department department : childList){
            department.setTreeList(getChilde(department.getId(), rootList));
        }
        if (childList.size() == 0){
            return null;
        }
        return childList;
    }
    @Override
    public void remakeDepartment() {
        List<Department> data = departmentDao.getAll();
        for (int i=0;i<data.size();i++){
            if (departmentDao.getOne(data.get(i).getSuper_id())==null&&data.get(i).getSuper_id()!=0){
                departmentDao.delete(data.get(i).getId());
            }
        }
    }

}
